package team.bluepen.supermarket.data.entity;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import team.bluepen.supermarket.kafka.KafkaDeserializer;
import team.bluepen.supermarket.kafka.KafkaSerializer;

import java.beans.ConstructorProperties;
import java.io.Serializable;
import java.util.Objects;

/**
 * @author RollW
 */
public class ProductNameAmount implements Serializable {
    @JsonProperty("name")
    private final String name;

    @JsonProperty("amount")
    private final int amount;

    @ConstructorProperties({"name", "amount"})
    public ProductNameAmount(String name, int amount) {
        this.name = name;
        this.amount = amount;
    }

    public String getName() {
        return name;
    }

    public int getAmount() {
        return amount;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        ProductNameAmount that = (ProductNameAmount) o;
        return amount == that.amount && Objects.equals(name, that.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, amount);
    }

    public static KafkaSerializer<ProductNameAmount> serializer() {
        return Serial.INSTANCE;
    }

    public static KafkaDeserializer<ProductNameAmount> deserializer() {
        return Serial.INSTANCE;
    }

    private static class Serial implements KafkaSerializer<ProductNameAmount>,
            KafkaDeserializer<ProductNameAmount> {
        private final ObjectMapper objectMapper = new ObjectMapper();

        @Override
        public String serialize(ProductNameAmount productNameAmount) {
            try {
                return objectMapper.writeValueAsString(productNameAmount);
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }
        }

        @Override
        public ProductNameAmount deserialize(String s) {
            try {
                return objectMapper.readValue(s, ProductNameAmount.class);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            }
        }

        private static final Serial INSTANCE = new Serial();
    }


}
